--<<<
format debug "--  Compiling Conductor Class . . .\n" undefined undefined

if (not isDefined Instrument) do (
	format debug "--!! ERROR Instrument must be defined before Conductor !!\n" undefined
)

class Conductor (TwoDShape)
inst vars
	myClock
	mouseDown
	loopCB
	state
	duration
end

method init self {class Conductor} #rest args #key castNum: currScene: dirInfo:->
(
	local cast := dirInfo[@cast]
	local bmp := cast[castNum].boundary
	apply nextMethod self boundary:bmp args
	local clockObj := new ConductorClock owner:self
	clockObj.scale := 100
	clockObj.rate := 1
	currScene.sceneMasterClock := clockObj
	self.state := @noSync
	self.myClock := clockObj
	self.duration := (0 as time)
	return self
)

method mouseDownAction self {class Conductor} theInterest theEvent ->
(
	local myClock := self.myClock
	local cb := self.loopCB
	case self.state of
		@noSync: (
						if myClock.slaveClocks.size > 0 do (
							self.state := @sync
							myClock.rate := 0
							myClock.time := 0
							if cb <> undefined do (
								cancel cb
								cb := undefined
							)
							if cb = undefined do (
								self.loopCB := addTimeCallback myClock gotoBegin myClock #() (self.duration + (2*myClock.scale)) false
								print "Master Callback added"
							)
							for sc in myClock.SlaveClocks do (
								sc.time := 0
								syncYourself sc @sync
							)
							myClock.rate := 1
						)
						)
		@sync: 		(
						self.state := @noSync
						if cb <> undefined do (
							cancel cb
							print "Master Callback added"
							self.loopCB = undefined
						)
						for sc in myClock.SlaveClocks do syncYourself sc  @noSync					
						)
	end --case
	format debug "state  of Master to %2\n" #(undefined, self.state) #(@unadorned,@unadorned)
)

method hook self {class Conductor} ->
(
	self.state := @noSync
	local mouseDev := new MouseDevice
	local mdEvnt := self.mouseDown
	if not (isAKindOf mdEvnt MouseDownEvent) do (
		mdEvnt := new MouseDownEvent
		mdEvnt.eventReceiver := mouseDownAction
		mdEvnt.authorData := self
		mdEvnt.device := mouseDev
		mdEvnt.presenter := self
		self.mouseDown := mdEvnt
	)
	if not mdEvnt.advertised do addEventInterest mdEvnt
)

method unhook self {class Conductor} ->
(
	local mdEvnt := self.mouseDown
	if mdEvnt.advertised do removeEventInterest mdEvnt
	local cb := self.loopCB
	if cb <> undefined do (
		cancel cb
		self.loopCB := undefined
	)
)

method instrumentAdded self {class Conductor} newInstrument->
(
	local myDuration := self.duration
	local newDuration := newInstrument.duration
	if newDuration > myDuration do (
		self.duration := newDuration
	)
)
#(Conductor, #("duration"), #("stateGetter","hook","unhook"))
-->>>
